﻿<?

header("Content-Type: text/html; charset=utf-8");

/* Database connection function */
function connectDB()
{
    mysql_connect("localhost","root","");
    mysql_selectdb("rare");    
} /* End of Database connection function */


/* getElementById Function */

/* Search function. Returns array. */
function search( $table, $cols, $query, $mode)
{
    if($mode == "FULLTEXT")
     $query = mysql_query("SELECT * FROM ".$table." WHERE MATCH  (".$cols.")  AGAINST ('".addslashes($query)."')");
    elseif($mode == "LIKE")
     $query = mysql_query("SELECT * FROM ".$table." WHERE (".$cols.") LIKE ('%".addslashes($query)."%')"); 
     
    while($result = mysql_fetch_array($query))
     $arraySearchResults[] = $result;
    return $arraySearchResults;  
} /* End of search function */



function str_separ($text, $counttext, $start = 0) {
    $sep = ' ';
     $words = explode($sep, $text);
     if ( count($words) > $counttext )
         $text = join($sep, array_slice($words, $start, $counttext));
     return $text;
 }


function showSearchResults( $query )
{
    $results = search("queries", "query, body", $query, "FULLTEXT");
    if($results)
     {
        echo "<h3>Возможно мы знаем где искать:</h3>";
     foreach($results as $key=>$result)
        
        $pos = stripos($result['body'], $query);
        if(($pos - 100) >=0 )
         $pos = $pos - 100;
        else $pos = 0;
        $prepareDesc =  substr($result['body'], $pos); 
                      
         if(strlen($prepareDesc) > 150)
          $prepareDesc = "...".str_separ($prepareDesc, 30, 1)."...";
                    
           $prepareDesc = str_ireplace($query, "<b>".$query."</b>", $prepareDesc);
         
         
        echo "<a href='index.php?id=".$result['id']."' class='link'>".$result['query']."</a><div class='simple'>".$prepareDesc."</div><br>";
      }
}

if($_GET['query'])
  showSearchResults( iconv("cp1251", "utf-8", $_GET['query']) ); 
?>